<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { SystemSumIcon } from 'tdesign-icons-vue-next';
import { 
  Tooltip as TTooltip,
  Select as TSelect,
  Button as TButton,
  Avatar as TAvatar 
} from 'tdesign-vue-next';
import {
  Chat as TChat,
  ChatContent as TChatContent,
  ChatLoading as TChatLoading,
  ChatSender as TChatSender
} from '@tdesign-vue-next/chat';
import {
  Plus,
  Phone,
  ChatRound,
  Delete
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { getFormattedDate } from '@/utils/date';
import { aiGetConversationListService, aiGetConversationMsgListService, aiPostConversationService } from '@/api/ai';
import { useUserStore } from '@/stores';

onMounted(() => {
  document.documentElement.classList.remove('dark');
})
onUnmounted(() => {
  document.documentElement.classList.add('dark');
})

const router = useRouter();
const userStore = useUserStore();

/* 聊天列表 */
const selectChatId = ref(null);

// 聊天列表数据
const chatList = ref([]);
const chatMap = ref(new Map());
const getChatList = async () => {
  const list = (await aiGetConversationListService()).data.data;
  chatList.value = list;

  for (const e of chatList.value) {
    e.active = false;
    e.msgList = [];
    chatMap.value.set(e.conversationId, e);
  }
}
getChatList();

// 新建聊天
const newChat = async () => {
  const newId = (await aiPostConversationService()).data.data;
  const newChat = {
    conversationId: newId,
    title: `新对话 ${-newId}`,
    date: getFormattedDate(),
    active: true,
    msgList: []
  };
  chatList.value.unshift(newChat);
  chatMap.value.set(newId, newChat);

  if (selectChatId.value) {
    chatMap.value.get(selectChatId.value).active = false;
  }
  selectChatId.value = newId;
  chatMap.value.get(selectChatId.value).active = true;
}

// 删除聊天
const deleteChat = (id) => {
  const index = chatList.value.findIndex(c => c.id === id)
  if (index !== -1) {
    chatList.value.splice(index, 1)
    // 如果删除的是当前激活的聊天，激活第一个
    if (chatList.value.length > 0 && chatList.value[index]?.active) {
      chatList.value[0].active = true
    }
  }
}

// 激活聊天
const activateChat = async (id) => {
  if (selectChatId.value) {
    chatMap.value.get(selectChatId.value).active = false;
  }
  const currentChat = chatMap.value.get(id);
  currentChat.active = true;
  selectChatId.value = id;
  currentChat.msgList = (await aiGetConversationMsgListService(selectChatId.value)).data.data;
}

/* 聊天 */
const loading = ref(false);

const allowToolTip = ref(false);
const chatSenderRef = ref(null);
const inputValue = ref('');
const selectOptions = [
  {
    label: 'Deepseek',
    value: 'deepseek-r1'
  },  
  {
    label: '依托',
    value: 'yt'
  }
];
const selectValue = ref({
  label: 'Deepseek',
  value: 'deepseek-r1'
});
const isChecked = ref(false);
const checkClick = () => {
  isChecked.value = !isChecked.value;
};

const inputEnter = async function () {
  if (loading.value) {
    return;
  }
  if (!inputValue.value) return;
  if (!selectChatId.value) {
    await newChat();
  }
  loading.value = true;

  const msg = inputValue.value;
  inputValue.value = '';

  const msgList = chatMap.value.get(selectChatId.value).msgList;
  msgList.unshift({
    role: 'user',
    content: msg,
  })

  if (selectValue.value.value === 'yt') {
    msgList.unshift({
      role: 'assistant'
    })  
    setTimeout(() => {
      loading.value = false;
      msgList[0].content = "<img src='http://127.0.0.1:18888/YH.png'>";
    }, 3000);
  } else {
    msgList.unshift({
      role: 'assistant',
      content: ''
    })
    const eventSource = new EventSource(`/ai/api/public/llm/chat/${selectChatId.value}?token=${userStore.token}&msg=${encodeURIComponent(msg)}`)
    
    eventSource.onmessage = (event) => {
      msgList[0].content += event.data;
    }
    
    eventSource.onerror = () => {
      loading.value = false
      eventSource.close()
    }
  }
 
};

</script>

<template>
  <el-container>
    <el-aside class="sidebar" width="20vw">
      <!-- 顶部区域 -->
      <div class="header">
        <img class="icon" src="/src/assets/YH_logo.png" @click="router.push('/')">
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="newChat"
          class="new-chat-btn"
        >
          新建对话
        </el-button>
      </div>

      <!-- 聊天列表 -->
      <div class="chat-list">
        <div 
          v-for="chat in chatList" 
          :key="chat.conversationId"
          :class="['chat-item', { active: chat.active }]"
          @click="activateChat(chat.conversationId)"
        >
          <el-icon class="chat-icon"><ChatRound /></el-icon>
          <div class="chat-info">
            <div class="chat-title">{{ chat.title }}</div>
            <div class="chat-date">{{ chat.date }}</div>
          </div>
          <el-icon 
            class="delete-icon"
            @click.stop="deleteChat(chat.conversationId)"
          >
            <Delete />
          </el-icon>
        </div>
      </div>

      <!-- 底部操作区域 -->
      <div class="footer">
        <el-button :icon="Phone" text class="phone-btn" @click="router.push('/_ai/voice-chat')">
          语音聊天
        </el-button>
      </div>
    </el-aside>
    <el-main>
      <t-chat
        class="chat"
        :clear-history="false"
        :reverse="true"
        :data="chatMap.get(selectChatId)?.msgList"
      >
        <template #name="{ item, index }">
          <span></span>
        </template>
        <template #datetime="{ item, index }">
          <span></span>
        </template>
        <template #avatar="{ item, index }">
          <t-avatar size="large" shape="circle" :image="item.role === 'user' ?  'http://47.121.24.225:19999/yh/nailong.gif' : '/src/assets/YH_logo.png'" />
        </template>
        <template #content="{ item, index }" >
          <div>
            <t-chat-loading animation="moving" text="思考中..." v-if="item.content === undefined || item.content.length === 0"/>
            <t-chat-content :content="item.content" v-else/>
          </div>
        </template>
        <template #footer>
          <t-chat-sender
            ref="chatSenderRef"
            v-model="inputValue"
            class="chat-sender"
            :textarea-props="{
              placeholder: '请输入消息...',
            }"
            :loading="loading"
            @send="inputEnter"
          >
            <template #suffix="{ renderPresets }">
              <component :is="renderPresets([{ name: 'uploadImage' }])" />
            </template>
            <template #prefix>
              <div class="model-select">
                <t-tooltip v-model:visible="allowToolTip" content="切换模型" trigger="hover">
                  <t-select
                    v-model="selectValue"
                    :options="selectOptions"
                    value-type="object"
                    @focus="allowToolTip = false"
                  ></t-select>
                </t-tooltip>
                <t-button class="check-box" :class="{ 'is-active': isChecked }" variant="text" @click="checkClick">
                  <SystemSumIcon />
                  <span>深度思考</span>
                </t-button>
              </div>
            </template>
          </t-chat-sender>
        </template>
      </t-chat>
    </el-main>
  </el-container>
</template>

<style lang="scss" scoped>
.el-main {
  height: 100vh;
}

.chat {
  height: 100%;
  padding: 0px;
}

:deep(.t-chat__list) {
  padding: 25px 20vw 0px 0px;
}

.chat-sender {
  padding: 10px 20vw 0px 0px;
  .btn {
    color: var(--td-text-color-disabled);
    border: none;
    &:hover {
      color: var(--td-brand-color-hover);
      border: none;
      background: none;
    }
  }
  .btn.t-button {
    height: var(--td-comp-size-m);
    padding: 0;
  }
  .model-select {
    display: flex;
    align-items: center;
    :deep(.t-select) {
      width: 112px;
      height: var(--td-comp-size-m);
      margin-right: var(--td-comp-margin-s);
      .t-input {
        border-radius: 32px;
        padding: 0 15px;
      }
      .t-input.t-is-focused {
        box-shadow: none;
      }
    }
    .check-box {
      width: 112px;
      height: var(--td-comp-size-m);
      border-radius: 32px;
      border: 0;
      background: var(--td-bg-color-component);
      color: var(--td-text-color-primary);
      box-sizing: border-box;
      flex: 0 0 auto;
      :deep(.t-button__text) {
        display: flex;
        align-items: center;
        justify-content: center;
        span {
          margin-left: var(--td-comp-margin-xs);
        }
      }
    }
    .check-box.is-active {
      border: 1px solid var(--td-brand-color-focus);
      background: var(--td-brand-color-light);
      color: var(--td-text-color-brand);
    }
  }
}

.sidebar {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: white;
  color: #334155;
  border-right: 1px solid #e2e8f0;
  padding: 20px 15px;
  transition: all 0.3s ease;
}

.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f1f5f9;
  user-select: none;
  
  .icon {
    max-width: 20%;
    padding-bottom: 10px;
    cursor: pointer;
  }

  .new-chat-btn {
    width: 100%;
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
    border: none;
    border-radius: 12px;
    padding: 12px 0;
    font-weight: 500;
    letter-spacing: 0.5px;
    color: white;
    box-shadow: 0 4px 6px rgba(99, 102, 241, 0.2);
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 12px rgba(99, 102, 241, 0.3);
    }
  }
}

.chat-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 5px;
  margin-bottom: 20px;
  
  .chat-item {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    border-radius: 12px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    background: #f8fafc;
    border: 1px solid #f1f5f9;
    
    &:hover {
      background: #f1f5f9;
      border-color: #e2e8f0;
      
      .delete-icon {
        opacity: 1;
      }
    }
    
    &.active {
      background: linear-gradient(90deg, rgba(99, 102, 241, 0.1) 0%, rgba(139, 92, 246, 0.05) 100%);
      border-left: 3px solid #6366f1;
    }
    
    .chat-icon {
      font-size: 18px;
      color: #94a3b8;
      margin-right: 12px;
    }
    
    .chat-info {
      flex: 1;
      overflow: hidden;
      
      .chat-title {
        font-size: 0.95rem;
        font-weight: 500;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-bottom: 4px;
        color: #0f172a;
      }
      
      .chat-date {
        font-size: 0.75rem;
        color: #94a3b8;
      }
    }
    
    .delete-icon {
      opacity: 0;
      color: #94a3b8;
      transition: all 0.2s ease;
      padding: 5px;
      border-radius: 6px;
      
      &:hover {
        color: #ef4444;
        background: rgba(239, 68, 68, 0.1);
      }
    }
  }
}

.footer {
  border-top: 1px solid #f1f5f9;
  padding-top: 15px;
  
  .phone-btn {
    width: 100%;
    justify-content: center;
    color: #64748b;
    font-weight: 500;
    padding: 10px;
    border-radius: 10px;
    
    &:hover {
      color: #6366f1;
      background: #f1f5f9;
    }
  }
}

/* 滚动条样式 */
.chat-list::-webkit-scrollbar {
  width: 6px;
}

.chat-list::-webkit-scrollbar-track {
  background: transparent;
}

.chat-list::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    flex-direction: column;
    height: auto;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
    border-right: none;
    border-bottom: 1px solid #e2e8f0;
  }
  
  .preview-content {
    padding: 30px 15px;
  }
}
</style>